<template>
  <div>
    <FilterTable
      ref="tableLabour"
      height="auto"
      :columns="columnsLabour"
      columnsRef="roAssignModelLabourTable"
      :fetchapi="fetchapiLabour"
      :params="fetchParamsLabour"
      selectionType="single"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columnsLabour = columns)"
      :onRowSelectChange="SelectChange"
      :onSyncTableData="columns => (this.allColumns = columns)"
    />
    <FilterTable
      ref="tableLabourDeatil"
      height="auto"
      :maxHeight="710"
      :columns="columnsLabourDeatil"
      columnsRef="roAssignModelLabourDeatilTable"
      :dataSource="dataSource"
      selectionType="single"
      :onColumnsChange="columns => (this.columnsLabourDeatil = columns)"
      :onSyncTableData="columns => (this.allColumnsDeatil = columns)"
    />
    <FilterTable
      ref="tablePart1"
      :columns="columnsPart"
      height="auto"
      :maxHeight="710"
      columnsRef="roAssignModelPartTable1"
      :fetchapi="fetchapiPart"
      :params="fetchParamsPart"
      :isSelectColumn="false"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columnsPart = columns)"
    />

    <BaseDialog :visible.sync="partDetail" :title="'发料明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partDetailModel :roNo="this.roNo" @close="closeDialog" />
    </BaseDialog>

    <BaseDialog :visible.sync="completed" :title="'竣工'" destroyOnClose width="450px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <completedModel :Mileage="this.roNo" @close="closeCompleted" />
    </BaseDialog>

    <BaseDialog :visible.sync="addAssign" :title="'派工'" destroyOnClose width="350px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addAssignModel :LabourColumns="LabourColumns" :manhour="manhour" :Type="Type" :rotime="rotime" :assignType="assignType" :allUsers="this.allUsers" @close="closeAddAssign" />
    </BaseDialog>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button size="small" type="primary" @click="partDetailClick">发料明细</el-button>
      <el-button size="small" type="primary" @click="addAssignClick">新增派工</el-button>
      <el-button size="small" type="primary" @click="deleteAssignClick">删除项目派工</el-button>
      <!-- <multiuse-button size="small" type="primary" :auth-list="auths" auth-mark="/repair/workManage/repairDispatch/Completion" @click="completedClick">竣工</multiuse-button> -->
      <el-button size="small" type="primary" @click="closePage">取消</el-button>
    </div>
  </div>
</template>

<script>
import {
  queryRoLabourByRoNOss,
  queryFinished,
  queryRoAssignByRoNOs,
  selectWorkGroupDicts,
  maintainRepairAssignComplete,
  deleteAssign,
  queryRoAssign,
  queryRoRepairPartByTag
} from '@/api/repair/repairAssign/repairAssign';
import partDetailModel from './partDetailModel';
import { getDealerUser } from '@/api/part/partInventory/partInventory/index.js';
import completedModel from './completedModel';
import addAssignModel from './addAssignModel';
import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
export default {
  name: 'roAssignModel',
  components: {
    partDetailModel,
    completedModel,
    addAssignModel
  },
  mixins: [dictionary, authority],
  props: ['roNo', 'assignType'],
  data() {
    this.allUsers = [];
    return {
      fetchParamsLabour: {},
      LabourColumns: [],
      allColumns: [],
      dataSource: [],
      fetchapiLabour: queryRoLabourByRoNOss,
      fetchapiPart: queryRoRepairPartByTag,
      fetchParamsPart: {},
      allColumnsDeatil: [],
      partDetail: false,
      completed: false,
      addAssign: false,
      Type: '',
      columnsLabour: this.createTableColumnsLabour(),
      columnsLabourDeatil: this.createTableColumnsLabourDeatil(),
      columnsPart: this.createTableColumnsPart(),
      serviceAdvisorData: [], // 存人员的信息
      rotime: '',
      tag: '',
      tag1: '',
      manhour: ''
    };
  },
  created() {
    let roNo = this.roNo[0].RO_NO;
    this.fetchParamsLabour = Object.assign({}, { roNo: roNo }, { xhrAbort: false });
    this.fetchParamsPart = Object.assign({}, { roNo: roNo }, { xhrAbort: false });
  },
  mounted() {
    this.getLabour();
    this.queryLi();
    this.getEmp();
    this.serviceConsultant();
    this.rotime = this.roNo[0].RO_CREATE_DATE;
  },
  methods: {
    createTableColumnsPart() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件数量',
          dataIndex: 'PART_QUANTITY',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input',
          summation: true
        },
        {
          title: '计量单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '配件销售单价',
          dataIndex: 'PART_SALES_PRICE',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
          // summation: true,
          precision: 2
        },
        {
          title: '配件销售金额',
          dataIndex: 'PART_SALES_AMOUNT',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '领料人',
          dataIndex: 'RECEIVER',
          sorter: true,
          filter: true,
          width: 110,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        }
      ];
    },
    createTableColumnsLabour() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '检查结果',
        //   dataIndex: 'TROUBLE_DESC',
        //   sorter: true,
        //   filterType: 'input'
        // },
        {
          title: '故障原因',
          dataIndex: 'TROUBLE_CAUSE',
          sorter: true,
          width: 100,
          filterType: 'input'
        },
        {
          title: '是否派工',
          dataIndex: 'ASSIGN_TAG',
          sorter: true,
          width: 100,
          render: props => {
            return <span>{this.createDictText(props.row.ASSIGN_TAG, '1004')}</span>;
          }
        },
        {
          title: '是否委外',
          dataIndex: 'CONSIGN_EXTERIOR',
          dictItems: this.createDictList(1004),
          filter: true,
          filterType: this.createDictList(1004)
        },
        {
          title: '维修项目代码',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          width: 120,
          filterType: 'input'
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true,
          width: 250,
          filterType: 'input'
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          width: 110,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          width: 110,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '责任技师',
          dataIndex: 'TECHNICIAN_NAME',
          sorter: true,
          width: 100,
          filterType: 'input',
          editType: 'select',
          editItems: []
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '是否不修',
          dataIndex: 'NEEDLESS_REPAIR',
          sorter: true,
          width: 100,
          render: props => {
            return <span>{this.createDictText(props.row.NEEDLESS_REPAIR, '1004')}</span>;
          }
        }
      ];
    },
    createTableColumnsLabourDeatil() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'mx',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editRoAssign(props)}>
                  编辑
                </el-button>
              </div>
            );
          }
          // render: props => {
          //   return <el-button icon="el-icon-document" onClick={() => this.editRoAssign(props)}></el-button>;
          // }
        },
        {
          title: '责任技师',
          dataIndex: 'TECHNICIAN',
          sorter: true,
          filter: true,
          width: 130,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '工位',
          dataIndex: 'LABOUR_POSITION_CODE',
          sorter: true,
          filter: true,
          width: 130,
          editable: false,
          editType: 'select',
          editItems: []
          // render: porps => {
          //   return <span>{this.createDictText(porps.row.LABOUR_POSITION_CODE, '8004')}</span>;
          // }
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '派工时间',
          dataIndex: 'ASSIGN_TIME',
          sorter: true,
          width: 135,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '开工时间',
          dataIndex: 'ITEM_START_TIME',
          sorter: true,
          width: 135,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '预计完工时间',
          dataIndex: 'ESTIMATE_END_TIME',
          sorter: true,
          width: 135,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '是否完工',
          dataIndex: 'FINISHED_TAG',
          sorter: true,
          width: 100,
          render: props => {
            return <span>{this.createDictText(props.row.FINISHED_TAG, '1004')}</span>;
          }
        },
        {
          title: '完工时间',
          dataIndex: 'ITEM_END_TIME',
          sorter: true,
          width: 135,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '检验人',
          dataIndex: 'CHECKER',
          sorter: true,
          filter: true,
          width: 100,
          editable: true,
          editType: 'select',
          editItems: []
          //  render: props => {
          //   return <span>{this.getEmployeeName(props.row.CHECKER)}</span>;
          // }
        }
        // {
        //   title: '检验人',
        //   dataIndex: 'CHECKER',
        //   sorter: true,
        //   filter: true,
        //   width: 100,
        //   editable: true,
        //   editType: 'select',
        //   editItems: []
        //   // render: props => {
        //   //   return <span>{this.getEmployeeName(props.row.CHECKER)}</span>;
        //   // }
        // }
      ];
    },
    // 选择
    SelectChange(row) {
      //  this.items.push(row.ITEM_ID);
      console.log('调用了...', row);
      let item = [];
      let str = "'";
      for (const val of row) {
        item.push(str + val.ITEM_ID + str);
      }
      if (row.length > 0) {
        this.query(item);
        this.LabourColumns = row;
      } else {
        this.LabourColumns = [];
        this.dataSource = [];
      }
      this.tag = 0;
      // tag 选择多个项目时 多选获取多大得工时数据
      // this.tag = row[0].ASSIGN_LABOUR_HOUR;
      for (var i = 0; i < row.length; i++) {
        this.tag = this.tag + row[i].ASSIGN_LABOUR_HOUR;
        // if (this.tag < row[i].ASSIGN_LABOUR_HOUR) {
        //   this.tag = row[i].ASSIGN_LABOUR_HOUR; // 获取多选中最大得派工工时
        // }
      }
    },
    async query(val) {
      let res = await queryRoAssign(val);
      this.dataSource = res.data.rows;
      let assignLabourHour = 0;
      let ch = res.data.rows.length;
      this.tag1 = 0;
      if (ch != 0) {
        for (var i = 0; i < this.dataSource.length; i++) {
          this.tag1 += assignLabourHour + this.dataSource[i].ASSIGN_LABOUR_HOUR;
        }
        // this.tag1 = assignLabourHour;
        this.manhour = this.tag - this.tag1;
        if (this.manhour <= 0) {
          this.manhour = 0;
        }
      } else {
        this.manhour = this.tag;
      }
    },
    async queryLi() {
      // 工位
      const sfqfRes = await selectWorkGroupDicts();
      console.log(sfqfRes.data);
      this.columnsLabourDeatil.find(item => item.dataIndex === 'LABOUR_POSITION_CODE').editItems = sfqfRes.data.map(x => ({ text: x.LABOUR_POSITION_NAME, value: x.LABOUR_POSITION_CODE }));
    },
    // 获取员工信息并转义
    async getEmp() {
      const res = await getDealerUser();
      // this.serviceAdvisorData = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
      this.allUsers = res.data.map(x => ({ value: x.userId + '', text: x.employeeName }));
      this.columnsLabourDeatil.find(item => item.dataIndex === 'CHECKER').editItems = this.allUsers;
      this.columnsLabourDeatil.find(item => item.dataIndex === 'TECHNICIAN').editItems = this.allUsers;
      this.columnsLabour.find(item => item.dataIndex === 'TECHNICIAN_NAME').editItems = this.allUsers;
      this.columnsPart.find(item => item.dataIndex === 'RECEIVER').editItems = this.allUsers;
    },
    // 转换数据
    // getEmployeeName(userId) {
    //   const item = this.serviceAdvisorData.find(x => {
    //     return x.value == userId;
    //   });
    //   return item ? item.text : '';
    // },
    editRoAssign(props) {
      let list = [];
      this.Type = 'edit';
      list.push(props.row);
      this.LabourColumns = list;
      // this.LabourColumns = props.row;
      this.addAssign = true;
    },
    async getLabour() {
      let res = await queryRoLabourByRoNOss({ roNo: this.roNo[0].RO_NO });
      let itemId = res.data.rows[0].ITEM_ID;
      let ress = await queryRoAssignByRoNOs(itemId);
      let technician = { role: dictCode.TECHNICIAN }; // 指定技师
      const technicianRes = await searchRoleByCodes(technician);
      ress.data.rows.forEach(x => {
        technicianRes.data.forEach(y => {
          if (x.TECHNICIAN == y.userId) {
            x.TECHNICIAN = y.employeeName;
          }
        });
      });
      // this.dataSource = ress.data.rows;
      return res;
    },

    // async getLabourDeatil(id) {
    //   const res = await queryRoAssignByRoNOs(id);
    //   return res;
    // },
    async saveDialog() {
      await maintainRepairAssignComplete(this.topFilterList, '2');
    },
    // async onEnterEventFun(row) {
    //   let res = await queryRoAssignByRoNOs(row.ITEM_ID);
    //   this.dataSource = res.data.rows;
    // },
    partDetailClick() {
      this.partDetail = true;
    },
    addAssignClick() {
      if (this.LabourColumns.length > 0) {
        this.addAssign = true;
        this.Type = 'add';
      } else {
        this.$notify.error({ title: '提示信息', message: '请先选择数据!' });
      }
    },
    async completedClick() {
      console.log(this.roNo, '前台带出的状态');
      if (this.roNo[0].COMPLETE_TAG == 10041002) {
        if (this.roNo[0].ASSIGN_STATUS == 80591003) {
          let res = await queryFinished(this.roNo[0].RO_NO).then(res => {
            if (res.data == '1') {
              this.$notify.error({ title: '提示信息', message: '此工单存在未入账配件，不能竣工 !' });
            } else {
              this.completed = true;
            }
          });
        } else {
          this.$notify.error({ title: '提示信息', message: '存在未派工的项目，不能竣工!' });
        }
      } else {
        this.$notify.error({ title: '提示信息', message: '该工单已竣工，不能重复竣工!' });
      }
      //  this.$emit('completedClick');
    },
    async deleteAssignClick() {
      if (this.LabourColumns.length > 0) {
        let itemId = '';
        let assignId = '';
        this.LabourColumns.forEach(x => {
          if (x.ITEM_ID) itemId += x.ITEM_ID + ',';
        });
        this.allColumnsDeatil.forEach(x => {
          if (x.ITEM_ID) assignId += x.ASSIGN_ID + ',';
        });
        let json = {
          roNo: this.roNo[0].RO_NO,
          itemId: itemId,
          assignId: assignId
        };
        let res = await deleteAssign(json).then(() => {
          this.fetchParamsLabour = Object.assign({}, this.fetchParamsLabour); // 刷新表格
        });
      } else {
        this.$notify.error({ title: '提示信息', message: '请先选数据!' });
      }
    },
    closeCompleted() {
      this.completed = false;
      this.$emit('close', this.roNo[0]._uid);
    },
    closeAddAssign(val) {
      this.addAssign = false;
      // this.getLabour(); // 刷新表格
      // this.fetchParamsLabour = { xhrAbort: false }; // 刷新表格
      // this.SelectChange(this.LabourColumns);
      if (val == 'save') {
        this.fetchParamsLabour = Object.assign({}, this.fetchParamsLabour); // 刷新表格
      }
      // this.$emit('close', '1');
    },
    closeDialog() {
      this.partDetail = false;
    },
    closePage() {
      this.$emit('close', this.roNo[0]._uid);
    },
    // 售前人员接口数据
    async serviceConsultant() {
      let technician = { role: dictCode.TECHNICIAN }; // 指定技师
      let materiel = { role: dictCode.MATERIAL_AVAILABLE }; // 领料人
      const res = await searchRoleByCodes(technician);
      const materielSend = await searchRoleByCodes(materiel);
      let res1 = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      res1.push({ text: '合派', value: '合派' });
      // this.columnsPart.find(item => item.dataIndex === 'RECEIVER').editItems = materielSend.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    }
  }
};
</script>
